package com.yoke.assistant.bridge;

import android.content.Intent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.webkit.JavascriptInterface;

import com.orhanobut.logger.Logger;
import com.yoke.assistant.service.AssistantService;
import com.yoke.assistant.utils.AppUtil;
import com.yoke.assistant.utils.ListUtil;

import java.util.List;


public class JsApp {

    private final AssistantService service;

    public JsApp() {
        this.service = AssistantService.service;
    }

    @JavascriptInterface
    public void startApp(String packageName) {
        Intent intent = AppUtil.getLauncherIntent(packageName,
                AppUtil.sContext.getPackageManager());
        if (intent == null) {
            AppUtil.showToast("没有安装" + packageName);
            return;
        }
        AppUtil.sContext.startActivity(intent);
    }

    @JavascriptInterface
    public JsView findViewsById(String id) {
        AccessibilityNodeInfo node = service.findViewById(null, id);
        return new JsView(node);
    }

    @JavascriptInterface
    public List<AccessibilityNodeInfo> findViewsByText(String text) {
        List<AccessibilityNodeInfo> list = service.findViewByContainsText(text);
        Logger.d("name 匹配个数 %s : %d", text, list.size());
        return list;
    }

    @JavascriptInterface
    public List<AccessibilityNodeInfo> findViewsByClass(String className) {
        List<AccessibilityNodeInfo> list = service.findViewByClassName(className);
        Logger.d("name 匹配个数 %s : %d", className, list.size());
        return list;
    }

    @JavascriptInterface
    public void clickByText(String text) {
        List<AccessibilityNodeInfo> viewByContainsText =
                service.findViewByContainsText(text);
        System.out.println(viewByContainsText.size());
        AccessibilityNodeInfo first = ListUtil.first(viewByContainsText);
        if (first != null) {
            service.clickView(first);
        } else {
            Logger.w("can't find " + text);
        }
    }

    @JavascriptInterface
    public void speak(String text) {

    }

}
